﻿namespace ClassyBlog.DomainObjects
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;

    public class Category : IHasId, IHasTitle, IHasSlug
    {
        private readonly ICollection<Category> children;
        private Guid id;

        [DebuggerStepThrough]
        public Category()
        {
            children = new List<Category>();
            id = Guid.NewGuid();
        }

        public virtual Guid Id
        {
            [DebuggerStepThrough]
            get { return id; }

            [DebuggerStepThrough]
            set { id = value; }
        }

        public virtual string Title { get; set; }

        public virtual string Slug { get; set; }

        public virtual Category Parent { get; set; }

        public virtual ICollection<Category> Children
        {
            [DebuggerStepThrough]
            get { return children; }
        }

        public static Category Parse(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return null;
            }

            var categories = path.Split(
                new[] { Path.AltDirectorySeparatorChar },
                StringSplitOptions.RemoveEmptyEntries);

            Category root = null;
            Category parent = null;

            foreach (var category in categories.Select(
                name => new Category
                            {
                                Title = name,
                                Slug = name
                            }))
            {
                if (root == null)
                {
                    root = parent = category;
                    continue;
                }

                parent.Children.Add(category);
                category.Parent = parent;

                parent = category;
            }

            return parent;
        }
    }
}